<template>
    <div class="view">
        <nav-bar title="订单确认" @clickLeft="back" :fixed="false" :shadow="true">
            <div class="back" slot="left">
                <i class="iconfont icon-fanhui"></i>
            </div>
        </nav-bar>
        <div class="order-confirm-wrap">
            <cube-scroll :data="itemList">
                <div class="address-section" @click="selectAddress" v-if="address!==null">
                    <div class="order-address">
                        <span class="iconfont icon-unie65c"></span>
                        <div class="address-info">
                            <div class="address-info-top">
                                <span class="name">{{address.name}}</span>
                                <span class="mobile">{{address.phone}}</span>
                            </div>
                            <div class="address">{{address.region.province}} {{address.region.city}} {{address.region.region}} {{address.detail}}</div>
                            <div class="address-tip">请认真确认收货地址，以免造成不必要的麻烦！</div>
                        </div>
                        <div class="arrow">
                            <span class="cubeic-arrow"></span>
                        </div>
                    </div>
                </div>
                <div class="address-section" @click="toAddressEdit(0)" v-else>
                    <div class="no-address">请添加收货地址</div>
                </div>

                <div class="product-list">
                    <div class="product-section" v-for="(group,key,gIdx) in orderDataList" :key="key" :data-id="key">
                        <div class="product-section-header">
                            <!--                    <img class="shop-logo" src="http://duoduo.qibukj.cn/./Upload/Images/20190321/201903211727515.png"/>-->
                            <span class="name">{{group.supplierName}}</span>
                        </div>
                        <div v-for="(item,idx) in group.childList" :key="item.item_sku.item_id+'_'+item.item_sku.spec_sku_id">
                            <div class="order-product-item">
                                <img class="product-picture" :src="item.image[0].file_path+'?imageView2/0/h/100'">
                                <div class="right">
                                    <div class="title ellipsis-2">{{item.name}}</div>
                                    <span class="spec">{{item.item_sku.item_attr}}</span>
                                    <div class="price-box">
                                        <span class="price">￥{{item.item_price}}</span>
                                        <span class="number">x {{item.total_num}}</span>
                                    </div>
                                </div>
                                <!--                <div class="product-list-cell">-->
                                <!--                    <div class="product-list-cell-title">购买数量</div>-->
                                <!--                    <div class="product-list-cell-tip">-->
                                <!--                        <number-box :value='1' @change="numChange"></number-box>-->
                                <!--                    </div>-->
                                <!--                </div>-->
                            </div>
                            <div class="product-list-cell">
                                <div class="product-list-cell-title">配送方式</div>
                                <div class="product-list-cell-tip">
                                    {{item.delivery.method.text}}
                                </div>
                            </div>
                        </div>

                        <div class="product-list-cell">
                            <div class="product-list-cell-title">运费</div>
                            <div class="product-list-cell-tip">
                                {{Number(group.express_price)>0?(group.express_price+'元'):'包邮'}}
                            </div>
                        </div>
                        <div class="product-list-cell">
                            <div class="product-list-cell-title">订单备注</div>
                            <div class="product-list-cell-tip">
                                <input class="product-list-cell-note" type="text" placeholder="选填，请合理填写" v-model="group.remark"></input>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="product-order-other" v-if="itemList.length > 0">
                    <div class="product-order-other-list-cell">
                        <cube-checkbox position="right" :option="{disabled:pointDisable}" v-model="canUsePoints" @input="changeUsePointsStatus">
                            <div class="product-order-other-label">
                                <svg class="icon " aria-hidden="true">
                                    <use xlink:href="#icon-jinbi"></use>
                                </svg>
                                <div class="product-order-other-text">
                                    <div class="product-order-other-score-title">可用<span>{{usePoint}}</span>积分支付该商品</div>
                                    <div class="product-order-other-score-desc">当前账户积分：{{user.payPoints}}</div>
                                </div>
                            </div>
                        </cube-checkbox>
                    </div>
                </div>
            </cube-scroll>
        </div>
        <div class="order-confirm-footer">
            <div class="price-content">
                <span>总金额</span>
                <span class="price-tip">￥</span>
                <span class="price">{{orderData.order_pay_price}}</span>
                <span class="express">（运费:￥{{orderData.express_price}}）</span>
            </div>
            <div class="submit" @click="submitOrder">提交订单</div>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import NavBar from "@/components/aui/NavBar.vue";
    import NumberBox from "@/components/aui/NumberBox.vue";


    import CommonUnit from "@/unit/CommonUnit";

    @Component({
        components: {
            NavBar, NumberBox
        }
    })
    export default class OrderConfirm extends Scene {
        private address: any = null;
        private itemList: any[] = [];
        private orderData: any = {};
        private remark: string = "";
        private orderDataList: any = {};
        private canUsePoints: boolean = true;

        @State("UserStore")
        public user!: InterfaceUser;

        private changeUsePointsStatus(): void {
            this.$nextTick(() => {
                this.getOrderConfirmData();
            });
        }


        private get usePoint(): string {
            const price = Number(this.orderData.order_pay_price || 0);
            const point = Number(this.user.payPoints);
            if (point === 0) {
                this.canUsePoints = false;
            }
            if (point < price) {
                return String(this.user.payPoints);
            } else {
                return String(this.orderData.order_pay_price);
            }
        }

        private get pointDisable(): boolean {
            return Number(this.user.payPoints) === 0;
        }

        private get confirmParameter(): any {
            const parameter: any = {};
            if (String(this.$route.query.type) === "2") {
                parameter.cart_ids = this.$route.query.cartIds;
                parameter.coupon_id = [];
                parameter.remoark = [];
                for (const key in this.orderDataList) {
                    const couponObj: any = {};
                    const remarkObj: any = {};
                    parameter.coupon_id["supplier_" + String(this.orderDataList[key].supplierId)] = this.orderDataList[key].couponId;
                    parameter.remoark["supplier_" + String(this.orderDataList[key].supplierId)] = this.orderDataList[key].remark;
                    // parameter.couponIdObj = Object.assign(parameter.couponIdObj, couponObj);
                    // parameter.remarkObj = Object.assign(parameter.remarkObj, remarkObj);
                    // parameter.remark.splice(this.orderDataList[key].supplierId, 0, this.orderDataList[key].remark);
                }
                // parameter.coupon_id = JSON.stringify(parameter.couponIdObj);
                // parameter.remoark = JSON.stringify(parameter.remarkObj);

            } else {
                parameter.item_id = this.$route.query.itemId;
                parameter.item_num = this.$route.query.itemNum;
                parameter.item_sku_id = this.$route.query.itemSkuId;
                parameter.coupon_id = "";
                parameter.remark = this.remark;
            }
            parameter.pay_points = 0;
            if (this.canUsePoints) {
                parameter.pay_points = 1;
            }
            return parameter;
        }

        private get orderPayUrl(): any {
            if (String(this.$route.query.type) === "2") {
                return this.api.cartBuy;
            }
            return this.api.buyNow;
        }

        private back(): void {
            this.navigateBack();
        }

        private getOrderConfirmData(): void {
            Http.get(this.orderPayUrl, {...this.confirmParameter}, {token: this.user.token}).then((res) => {
                console.log(res);
                if (res.code === 1) {
                    this.address = res.data.address;
                    this.orderDataHandle(res.data.item_list);
                    this.orderData = res.data;

                } else {
                    (<any> this).$createToast({
                        txt: res.msg,
                        mask: true,
                        type: "error",
                        onTimeout: () => {
                            if (!CommonUnit.responseLoginVerification(res)) {
                                this.navigateLoginPage();
                            }
                        }
                    }).show();
                }
            });
        }

        private orderDataHandle(obj: any): boolean {
            console.log(obj);
            for (const oldkey in obj) {
                const objData: any = {};
                const oldKeyArray = oldkey.split("_");
                const newKey = `supplierId-${oldKeyArray[0]}`;
                objData.supplierName = oldKeyArray[1];
                // cartDataList[newKey].checked = false;
                objData.supplierId = oldKeyArray[0];
                objData.childList = [];
                objData.coupon_list = obj[oldkey].coupon_list;
                console.log(obj[oldkey]);
                objData.express_price = obj[oldkey].express_price;
                objData.order_pay_price = obj[oldkey].order_pay_price;
                objData.order_total_num = obj[oldkey].order_total_num;
                objData.order_total_price = obj[oldkey].order_total_price;
                objData.remark = "";
                objData.couponId = "";
                objData.childList.push(...obj[oldkey].item_list);
                this.itemList.push(...obj[oldkey].item_list);
                this.$set(this.orderDataList, newKey, objData);
            }
            return true;
        }

        private numChange(num: number): void {
            const query = this.$route.query;
            if (num !== Number(query.itemNum)) {
                query.itemNum = String(num);
                console.log(11);
                this.redirectTo({
                    name: "orderConfirm",
                    query: query
                });
            }

        }

        private mounted() {
            this.$nextTick(() => {
                this.getOrderConfirmData();
            });
        }

        private toAddressEdit(id: number): void {
            const query: any = {};
            if (id > 0) {
                query.id = id;
            }
            this.navigateTo({
                name: "addressEdit",
                query
            });
        }

        private selectAddress(): void {
            this.navigateTo({
                name: "addressList",
                query: {
                    referer: "orderConfirm"
                }
            });
        }

        private submitOrder(): void {
            if (!this.address) {
                (<any> this).$createToast({
                    txt: "请先去添加收货地址",
                    mask: true,
                    type: "error",
                    time: 3000,
                }).show();
                return;
            }
            let submitToast = (<any> this).$createToast({
                txt: "正在生成支付订单",
                time: 0,
                mask: true,
                zIndex: 201,
            }).show();
            Http.post(this.orderPayUrl, this.confirmParameter, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    if (String(res.data.status) === "0") {
                        this.redirectTo({
                            name: "orderChannel",
                            query: {
                                orderIds: res.data.ids.join(",")
                            }
                        });
                    } else {
                        submitToast = (<any> this).$createToast({
                            txt: "积分已经全额抵扣，您无需支付",
                            time: 1000,
                            mask: true,
                            zIndex: 201,
                            onTimeout: () => {
                                this.redirectTo({
                                    name: "orderList",
                                });
                            }
                        }).show();

                    }

                } else {
                    submitToast = (<any> this).$createToast({
                        txt: `${res.msg}`,
                        mask: true,
                        type: "error",
                        time: 3000,
                        onTimeout: () => {
                            if (!CommonUnit.responseLoginVerification(res)) {
                                this.navigateLoginPage();
                            } else {
                                this.redirectTo({
                                    name: "orderList"
                                });
                            }
                        }
                    }).show();
                }
            }).catch(() => {
                submitToast = (<any> this).$createToast({
                    time: 2000,
                    txt: "支付失败，请稍后～",
                    mask: true,
                    type: "error"
                }).show();
            });
        }
    }
</script>

<style scoped lang="stylus">
    .view
        background $theme-page-common-background-color;
        height 100vh;
        width 100vw;

        .order-confirm-wrap
            width 100vw;
            position relative;
            margin-top 1px;
            height calc(100vh - 45px - var(--safe-area-inset-top) - var(--safe-area-inset-bottom) - 50px);

        .address-section
            margin 10px;
            padding 15px 0;
            background #fff;
            position relative;
            border-radius 7px;

            .order-address
                display flex;
                align-items center;

                span.iconfont, .arrow
                    flex-shrink 0;
                    display flex;
                    align-items center;
                    justify-content center;
                    width 45px;
                    color #888;
                    font-size 22px;

                .arrow
                    width 30px !important;
                    font-size 14px;

                .address-info
                    display flex;
                    flex-direction column;
                    flex 1;
                    font-size: 14px;
                    color #333;

                    .address-info-top

                        .name
                            font-size 16px;
                            margin-right 10px;

                        .mobile
                            font-size 14px;
                            color #999


                    .address
                        margin-top 10px;
                        margin-right 10px;
                        font-size 13px;
                        line-height 1.5

                    .address-tip
                        font-size 10px;
                        margin-top 5px;
                        line-height 1.5;
                        color $theme-common-color;

        .product-section
            margin 0 10px 8px 10px;
            background #fff;
            padding-bottom 1px;
            border-radius 7px;
            overflow hidden;

            .product-section-header
                display flex;
                align-items center;
                height 42px;
                padding 0 15px;
                position relative;

                img.shop-logo
                    display block;
                    width 20px;
                    height 20px;
                    border-radius 20px;

                .name
                    font-size 12px;
                    color #111
                    margin-left 5px;

            .order-product-item
                display flex;
                margin 10px 15px;
                position relative;

                .product-picture
                    flex-shrink 0;
                    display block;
                    width 70px;
                    height 70px;
                    border-radius 3px;
                    position relative;

                .right
                    flex 1;
                    padding-left 12px;
                    overflow hidden;

                    .title
                        font-size 13px;
                        line-height 18px;
                        height 36px;
                        padding-right 70px;

                    .spec
                        font-size: 12px;
                        color: #666;
                        display block;
                        margin-top 4px;

                    .price-box
                        display flex;
                        align-items right;
                        padding-top 5px;
                        flex-direction column;
                        color #111
                        position absolute;
                        right 0;
                        top 0;

                        .price
                            margin-bottom 2px;
                            font-size 13px;
                            text-align right;

                        .number
                            font-size 12px;
                            color #333;
                            text-align right;
                            margin-top 3px;

            .product-list-cell
                display flex;
                align-items center;
                padding 5px 15px 5px 20px;
                line-height 35px;
                position relative;

                .product-list-cell-title
                    width 80px;
                    font-size 12px;
                    color #666;
                    margin-right 5px;
                    text-align right;

                .product-list-cell-tip
                    font-size 12px;
                    color #333;
                    flex 1;
                    padding-left 10px;

                    >>> .number-box
                        float right;

                    .product-list-cell-note
                        width 100%;
                        height 34px;
                        font-size 12px;

    .product-order-other
        margin 0 10px 10px 10px;
        background #fff;
        padding-bottom 1px;
        border-radius 7px;
        overflow hidden;

        .product-order-other-list-cell
            font-size 17px;

            .product-order-other-label
                display flex;
                align-items center;

                .icon
                    height 30px;
                    width 30px;
                    margin-right 5px;

                .product-order-other-text
                    color #333


                    .product-order-other-score-title
                        font-size 14px

                        span
                            color $theme-common-color;
                            font-weight 700px;

                    .product-order-other-score-desc
                        color #999
                        font-size 11px;


    .order-confirm-footer
        position fixed;
        left 0;
        bottom 0;
        display flex;
        align-items center;
        right 0;
        height calc(50px + var(--safe-area-inset-bottom));
        padding-bottom var(--safe-area-inset-bottom);
        justify-content space-between;
        font-size 15px;
        background-color #fff;
        z-index 198;
        color #333;
        box-shadow: 0 -1px 7px rgba(0, 0, 0, .05);

        .price-content
            padding-left 15px;
            font-size 12px;

            .price-tip
                color $theme-common-color;
                margin-left 4px;

            .price
                font-size 18px
                color $theme-common-color;

            .express
                padding-left 4px;
                font-size 10px;


    .submit
        display flex;
        align-items center;
        justify-content center;
        width 140px;
        height 38px;
        color #fff;
        font-size: 15px;
        background $theme-common-gradient;
        border-radius 38px;
        margin-right 10px;
        box-sizing content-box;

    .no-address
        line-height 50px;
        text-align center;
        font-size 16px;
        color $theme-warm-color;


</style>
